package wallet

import (
	"context"
	"fmt"
	"github.com/shopspring/decimal"
	"github.com/zeromicro/go-zero/core/mr"
	"github.com/zeromicro/go-zero/core/stores/redis"
	"go.uber.org/zap"
	gamePb "navi-mumbai/app/rpc/game/pb"
	ucPb "navi-mumbai/app/rpc/usercenter/pb"
	"navi-mumbai/app/rpc/wallet/pb"
	"navi-mumbai/common/ctxdata"
	"navi-mumbai/common/key/userkey"
	"navi-mumbai/common/key/walletkey"
	"navi-mumbai/common/rediskey"
	"navi-mumbai/common/xerr"

	"navi-mumbai/app/api/business/internal/svc"
	"navi-mumbai/app/api/business/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type LuckyRewardLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewLuckyRewardLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LuckyRewardLogic {
	return &LuckyRewardLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *LuckyRewardLogic) LuckyReward(req *types.LuckyRewardReq) (resp *types.LuckyRewardResp, err error) {
	uid := ctxdata.GetUidFromCtx(l.ctx)
	if uid != req.Uid || uid <= 0 {
		return nil, xerr.NewGrpcErrCodeMsg(xerr.RequestParamError, "invalid uid")
	}
	// 加分布式锁
	rkey := fmt.Sprintf(rediskey.RedisLockUserLuckyReward, uid)
	rl := redis.NewRedisLock(l.svcCtx.RedisClient, rkey)
	rl.SetExpire(2)
	b, err := rl.AcquireCtx(l.ctx)
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
		return nil, err
	}
	if !b {
		return nil, xerr.NewGrpcErrCodeMsg(xerr.RedisLockFail, "system busy")
	}

	defer func() {
		_, err2 := rl.ReleaseCtx(l.ctx)
		if err2 != nil {
			logx.WithContext(l.ctx).Errorf("RedisLock %s release err:%+v", rkey, err2)
			return
		}
	}()

	var rsp *pb.UserWalletBalanceResp
	var rsp2 *gamePb.GetGameWalletBalanceResp
	err = mr.Finish(
		func() error {
			var in pb.UserWalletBalanceReq
			in.Uid = req.Uid
			in.MoneyType = req.MoneyType
			var err2 error
			rsp, err2 = l.svcCtx.WalletUsersRpc.UserWalletBalance(l.ctx, &in)
			if err2 != nil {
				return err2
			}
			return nil
		},
		func() error {
			var in gamePb.GetGameWalletBalanceReq
			in.Uid = req.Uid
			in.ProviderId = req.ProviderId
			in.MoneyType = req.MoneyType
			var err2 error
			rsp2, err2 = l.svcCtx.GameWalletRpc.GetGameWalletBalance(l.ctx, &in)
			if err2 != nil {
				return err2
			}
			return nil
		},
	)
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
		return nil, xerr.NewGrpcErrCodeMsg(xerr.RequestParamError, err.Error())
	}

	// 低于最小值 领取
	var bB decimal.Decimal
	var gB decimal.Decimal
	var cd decimal.Decimal
	bB, err = decimal.NewFromString(rsp.Balance)
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
		return nil, xerr.NewGrpcErrCodeMsg(xerr.RequestParamError, err.Error())
	}
	gB, err = decimal.NewFromString(rsp2.Balance)
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
		return nil, xerr.NewGrpcErrCodeMsg(xerr.RequestParamError, err.Error())
	}
	cd, err = decimal.NewFromString(userkey.LuckyRewardMoneyAmount)
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
		return nil, xerr.NewGrpcErrCodeMsg(xerr.RequestParamError, err.Error())
	}

	if bB.GreaterThanOrEqual(cd) || gB.GreaterThanOrEqual(cd) {
		return &types.LuckyRewardResp{}, nil
	}

	// 是否增加礼物
	var in3 ucPb.AddUserRewardReq
	in3.Uid = req.Uid
	in3.RewardType = walletkey.UsingCurrencyType //userkey.RewardTypeGold
	in3.RewardAmount = userkey.LuckyRewardMoneyAmount
	in3.ActivityId = userkey.ActivityIdLuckyReward

	_, err = l.svcCtx.UcSys.AddUserReward(l.ctx, &in3)
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
		return nil, err
	}
	resp = &types.LuckyRewardResp{}
	return
}
